import requests
import traceback


class HttpRequest:

    def __init__(self, url, data=None, params=None, is_json=False, headers=None):
        self.url = url
        self.data = data
        self.params = params
        self.is_json = is_json
        self.headers = headers
        self.timeout = 3

    def get(self):
        try:
            if self.params is not None and self.data is None:
                response = requests.get(self.url, params=self.params,
                                        headers=self.headers, timeout=self.timeout)
            elif self.data is not None and self.params is None:
                response = requests.get(self.url, data=self.data,
                                        headers=self.headers, timeout=self.timeout)
            else:
                response = requests.get(self.url, data=self.data,
                                        params=self.params, headers=self.headers,
                                        timeout=self.timeout)
        except Exception as e:
            result = {"status": 400, "errorMsg": traceback.format_exc()}
        else:
            result = HttpRequest.__respone_dict(response)
        return result

    def post(self):
        if self.is_json:
            requests.post(self.url,json=self.data)
        else:
            requests.post(self.url,data=self.data)

    def put(self):
        pass 
    @staticmethod
    def __respone_dict(response):
        try:
            result = response.json()
        except Exception as e:
            result = response.text
        return result
